﻿using System.Collections.Generic;
using System.IO;
using System.Windows;
using dotNails.Util;
using EnvDTE;
using EnvDTE80;
using System.Reflection;
using System;
using System.Diagnostics;

using Microsoft.VisualStudio.CommandBars;

using dotNails.UI;

namespace dotNails.Commands {
	/// <summary>
	/// This command opens the Configurator UI.
	/// </summary>
	public class CreateDbmlCommand : CommandBase {
		#region Properties
		private MenuManager _menuManager;
		private CommandBarPopup _popupMenu;

		public MenuManager MenuManager {
			get { return _menuManager; }
			set { _menuManager = value; }
		}

		public CommandBarPopup PopupMenu {
			get { return _popupMenu; }
			set { _popupMenu = value; }
		}

		#endregion Properties

		#region Constructors
		public CreateDbmlCommand(DTE2 application, EnvDTE.AddIn addInInstance, MenuManager menuManager, CommandBarPopup popupMenu)
			: base(application, addInInstance, "CreateDbmlMenuCaption", "CreateDbmlMenuTooltipText") {
			this.MenuManager = menuManager;
			this.PopupMenu = popupMenu;
		}
		#endregion Constructors

		/// <summary>
		/// Opens the Create Dbml UI
		/// </summary>
		public override void Perform() {
			UIHierarchy hierarchy = Application.ToolWindows.SolutionExplorer;
			string folderPath = string.Empty;
			Project containingProject = null;
			string errorMessage = string.Empty;

			if (((object[])hierarchy.SelectedItems).Length > 1) {
				errorMessage = "Please select a single folder or project.";
			}
			else {
				foreach (UIHierarchyItem selectedItem in (object[]) hierarchy.SelectedItems) {
					folderPath = GetFolderPath(selectedItem);
					containingProject = AddInUtil.GetContiningProject(selectedItem.Object);
					break;
				}
			}

			try {
				ToolWindow toolWindow = new ToolWindow(Application, AddInInstance, MenuManager, PopupMenu, folderPath, containingProject, errorMessage);

				int left = this.Application.MainWindow.Left;
				int top = this.Application.MainWindow.Top;
				int width = this.Application.MainWindow.Width;
				int height = this.Application.MainWindow.Height;

				toolWindow.Left = left + width/2 - toolWindow.Width/2;
				toolWindow.Top = top + height/2 - toolWindow.Height/2;
				
				toolWindow.ShowDialog();
			}
			catch (Exception ex) {
				Debug.WriteLine(ex.Message);
				Debug.WriteLine(ex.StackTrace);
			}
		}

		/// <summary>
		/// Gets the folder (full) path.
		/// </summary>
		/// <param name="filePathName">File path.</param>
		/// <returns></returns>
		private string GetFolderPath(UIHierarchyItem item) {
			FileInfo info = new FileInfo(AddInUtil.GetFilePath(item.Object));
			return info.Directory.FullName;
		}
		
	}
}